package com.md.api.controller;

import com.md.api.common.utils.RedisUtil;
import com.md.api.entity.HttpResult;
import com.md.api.entity.dto.ComposeQueryDto;
import com.md.api.scheduled.SystemTask;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {


	@Resource
	RedisUtil redisUtil;
	@Autowired
	RedissonClient redisson;
	@Autowired
	SystemTask systemTask;
	@RequestMapping("/handleRoomPredetermine")
	public void handleRoomPredetermine() {
//		systemTask.handleRoomPredetermine();
	}
	@RequestMapping("/init")
	public HttpResult init(@RequestBody ComposeQueryDto dto) {
		String key = "product_" + dto.getSpuId();
		redisUtil.set(key, dto.getStatus());
		return HttpResult.OK;
	}


	@RequestMapping("/jmiter")
	public HttpResult buy(@RequestBody ComposeQueryDto dto) {
		String lock_key = "product_lock_" + dto.getSpuId();
		String key = "product_" + dto.getSpuId();
		RLock lock = redisson.getLock(lock_key);
		//try catch 设计是为了防止在执行业务的时候出现异常导致redis锁一直无法释放
		try {
			lock.lock();
			int count = Integer.parseInt(redisUtil.get(key).toString());
			if (count > 0) {
				redisUtil.set(key, --count);
				System.out.println(key + "商品购买成功，剩余库存" + count);
				return HttpResult.OK;
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return HttpResult.fail("暂无剩余");
	}

//	@RequestMapping("/prient")
//	public HttpResult prient(HttpServletRequest request, HttpServletResponse response) {
//		try {
//			drinkingCartService.printReceipts(request,response,"do20241126117554",1);
//			return HttpResult.OK;
//		}catch (Exception e){
//			return HttpResult.fail("打印失败！");
//		}
//	}


	@RequestMapping("/handleBirthCoupon")
	public HttpResult resetDrinkingSort(HttpServletRequest request, HttpServletResponse response) {
		try {
//			systemTask.handleBirthCoupon();
			return HttpResult.OK;
		}catch (Exception e){
			return HttpResult.fail("打印失败！");
		}
	}



}
